package com.restaurant.application.padtest.bandconsumer;

import com.google.common.base.Strings;
import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.base.data.ViewUpdate;
import com.nebutown.commonunits.dataface.DataModes;
import com.nebutown.commonunits.dataface.EntryTypes;
import com.nebutown.commonunits.dataface.FormShell;
import com.nebutown.commonunits.dataface.TableShell;
import com.nebutown.commonunits.dataface.definitions.*;
import com.nebutown.commonunits.uidataface.UIDataFace;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.commonunits.utils.JacksonUtils;
import com.nebutown.generation.basicdata.StringMap;
import com.restaurant.application.consumption.support.ConsumptionData;
import com.restaurant.application.consumption.support.OrderData;
import com.restaurant.application.goodscategory.support.CategoryData;
import com.restaurant.application.indexes.consumptionlist.AssistConsumptionList;
import com.restaurant.application.indexes.consumptionlist.support.BandBean;
import com.restaurant.application.indexes.customerlist.mysql.CustomerListBean;
import com.restaurant.application.indexes.customerlist.mysql.CustomerListCriteria;
import com.restaurant.application.indexes.customerlist.mysql.CustomerListImpl;
import com.restaurant.application.minifacade.data.IdBO;
import com.restaurant.application.padtest.bandconsumer.support.AbstractBandConsumer;

import java.util.List;
import java.util.Objects;

public class BandConsumerImpl extends AbstractBandConsumer {
    private final String ORDER_LIST = "orderList";
    private final String ORDER_DATA = "orderData";

    @Override
    public View getFullView() {
        addToSessionCache(ORDER_LIST, "");
        addToSessionCache(ORDER_DATA, "");
        PageForm form = newFormShell().getForm();
        return getSingleton(UIDataFace.class).newGenericForm(unitPosition(), form);
    }

    @Override
    public View getViewLead(ViewSpec spec) {
        return null;
    }

    @Override
    public ViewUpdate search(IdBO search, int[] seq) throws Exception {
        List<OrderData> orderList;
        if (Objects.nonNull(search) && !Strings.isNullOrEmpty(search.getId())) {
            orderList = getSingleton(AssistConsumptionList.class).getOrderList(new OrderData().withPosition(search.getId()));
        } else {
            orderList = getSingleton(AssistConsumptionList.class).getOrderList(new OrderData());
        }
        for (int i = 0; i < orderList.size(); i++) {
            orderList.get(i).setRecordId((long) i);
        }
        addToSessionCache(ORDER_LIST, JacksonUtils.obj2json(orderList));
        PageForm pageForm = newListShell(orderList, search).getForm();
        return returnView(getSingleton(UIDataFace.class).newGenericForm(unitPosition(), pageForm));
    }

    @Override
    public ViewUpdate bandCustomer(IdBO bandCustomer, int[] seq) throws Exception {
        List<CustomerListBean> search = getIndex(CustomerListImpl.class).search(new CustomerListCriteria().withPhoneEquals(bandCustomer.getId()), null, 1);
        if (search.size() > 0) {
            ConsumptionData consumptionData = new ConsumptionData().withCustomerName(search.get(0).getNickName()).withPhone(search.get(0).getPhone());
            String orderDataStr = getFromSessionCache(ORDER_DATA);
            OrderData orderData = new OrderData();
            if (!Strings.isNullOrEmpty(orderDataStr)) {
                orderData = JacksonUtils.json2pojo(orderDataStr, OrderData.class);
            }
            if (Objects.nonNull(orderData) && Objects.nonNull(orderData.getFactPrice())) {
                consumptionData.withFinalPrice(orderData.getFactPrice());
            }
            PageForm form = ensureForm(consumptionData).getForm();
            return returnView(getSingleton(UIDataFace.class).newGenericForm(unitPosition(), form));
        } else {
            return returnViewCall(buildViewCall(
                    unitPosition(),
                    "showErrorMessage",
                    null,
                    new StringMap().putData("errorMessage", "该用户还不是会员")));
        }
    }

    @Override
    public ViewUpdate bandCustomerPage(int[] seq) throws Exception {
        if (Objects.nonNull(seq) && seq.length > 0) {
            String orderList = getFromSessionCache(ORDER_LIST);
            List<OrderData> orderDataList = JacksonUtils.json2list(orderList, OrderData.class);
            OrderData orderData = orderDataList.get(seq[0]);
            addToSessionCache(ORDER_DATA, JacksonUtils.obj2json(orderData));
        }
        PageForm form = newBandForm(new IdBO()).getForm();
        return returnView(getSingleton(UIDataFace.class).newGenericForm(unitPosition(), form));
    }

    @Override
    public ViewUpdate ensurePrice(ConsumptionData ensurePrice, int[] seq) throws Exception {
        String orderDataStr = getFromSessionCache(ORDER_DATA);
        OrderData orderData = new OrderData();
        if (!Strings.isNullOrEmpty(orderDataStr)) {
            orderData = JacksonUtils.json2pojo(orderDataStr, OrderData.class);
        }
        if (Objects.nonNull(orderData.getFactPrice())) {
            ensurePrice.withOrderId(orderData.getNumber()).withTotalPrice(orderData.getTotalPrice()).withTime(orderData.getTime());
        }
        BandBean bean = new BandBean().withPhone(ensurePrice.getPhone()).withFinalPrice(ensurePrice.getFinalPrice()).withShopId("")
                .withTotalPrice(ensurePrice.getTotalPrice());
        getSingleton(AssistConsumptionList.class).bandToCustomer(bean);
        return returnView(getFullView());
    }


    private FormShell newFormShell() {

        FormShell formShell = new FormShell("消费关联", 1, 1);

        formShell.at(0, 0, "搜二维火订单")
                .buttonField(getPath(CMD_SEARCH), "", false);

        formShell.at(0, 1, "扫码会员")
                .buttonField(getPath(CMD_BANDCUSTOMERPAGE), "", false);
        return formShell;
    }


    private FormShell newBandForm(IdBO idBO) {
        FormShell formShell = new FormShell("关联客户", 1, 1);
        formShell.source(idBO, DataModes.EDIT);

        formShell.at(0, 0, "手机号")
                .getEntry(IdBO.FN_ID, idBO.getId())
                .placeHolder("请输入手机号")
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(true);
        formShell.at(0, 0, "绑定")
                .buttonField(getPath(CMD_BANDCUSTOMER), "", true);

        return formShell;
    }

    private FormShell ensureForm(ConsumptionData data) {

        FormShell formShell = new FormShell("消费关联", 3, 1);
        formShell.source(data, DataModes.EDIT);

        formShell.at(0, 0, "会员")
                .getEntry(ConsumptionData.FN_CUSTOMERNAME, data.getCustomerName())
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(false);

        formShell.at(1, 0, "手机号")
                .getEntry(ConsumptionData.FN_PHONE, data.getPhone())
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(false);

        formShell.at(2, 0, "消费")
                .getEntry(ConsumptionData.FN_FINALPRICE, Objects.isNull(data.getFinalPrice()) ? "" : data.getFinalPrice().toString())
                .simpleEntry(EntryTypes.DOUBLE)
                .notNull()
                .getContent().setEditable(true);

        formShell.at(3, 0, "提交")
                .buttonField(getPath(CMD_ENSUREPRICE), "", true);
        return formShell;
    }


    private FormShell newListShell(List<OrderData> collect, IdBO idBO) {

        PageInfo pageInfo = new PageInfo()
                .withPageNum(1)
                .withPageSize(100)
                .withTotalPage(1)
                .withTotalRecord(collect.size());
        FormShell formShell = new FormShell("消费关联", 2, 2);

        formShell.source(idBO, DataModes.EDIT);

        formShell.at(0, 0, "台号")
                .getEntry(IdBO.FN_ID, idBO.getId())
                .placeHolder("请输入台号")
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(true);

        TableShell<CategoryData> tableShell = new TableShell(CategoryData.class, collect).withPageInfo(pageInfo);

        tableShell.createColumn(OrderData.FN_TIME).withName("时间").cellCalculator(b -> {
            OrderData bean = (OrderData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(DateTimeUtils.toTime(bean.getTime())));
        });

        tableShell.createColumn(OrderData.FN_NUMBER).withName("二维火订单").cellCalculator(b -> {
            OrderData bean = (OrderData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getNumber()));
        });

        tableShell.createColumn(OrderData.FN_POSITION).withName("桌号").cellCalculator(b -> {
            OrderData bean = (OrderData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getPosition()));
        });

        tableShell.createColumn(OrderData.FN_TOTALPRICE).withName("消费金额").cellCalculator(b -> {
            OrderData bean = (OrderData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getTotalPrice().toString()));
        });

        tableShell.createColumn(OrderData.FN_FACTPRICE).withName("实付金额").cellCalculator(b -> {
            OrderData bean = (OrderData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(Objects.nonNull(bean.getFactPrice()) ? bean.getFactPrice().toString() : ""));
        });


        tableShell.createColumn("操作").withName("操作").cellCalculator(b -> {
            OrderData bean = (OrderData) b;
            return new CellData()
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("关联会员").withButtonPath(getPath(CMD_BANDCUSTOMERPAGE, bean.getRecordId()))));
        });

        formShell.at(1, 0, "消费列表")
                .large(3, 1)
                .getEntry("error", "")
                .tableEntry(tableShell);
        return formShell;
    }
}
